<template>
  <a-modal
    :title="title + $t('活动')"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
    :cancelText="$t('关闭')"
    v-drag
  >
    <template slot="footer">
      <a-button @click="handleCancel">{{ $t('取消') }}</a-button>
      <a-button v-if="!disabled" @click="handleOk" type="primary">{{ $t('保存') }}</a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form-model :rules="rules" :model="model" ref="dataForm" class="cus0-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
        <a-row>
          <a-col :span="24">
            <a-form-model-item :label="$t('发放类型')" prop="type">
              <a-select v-model="model.type" :disabled="disabled">
                <a-select-option value="">{{ $t('请选择') }}</a-select-option>
                <a-select-option v-for="(item, index) in list" :key="index" :value="item.value">{{
                  item.title
                }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item :label="$t('状态')" prop="state">
              <a-radio-group v-model="model.state" :disabled="disabled">
                <a-radio value="1">{{ $t('启用') }}</a-radio>
                <a-radio value="0">{{ $t('禁用') }}</a-radio>
              </a-radio-group>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item
              :label="$t('有效期')"
              required
              style="margin-bottom: 0"
            >
              <a-row>
                <a-col :span="10">
                  <a-form-model-item prop="beginTime">
                    <a-date-picker
                      :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
                      :placeholder="$t('请选择开始日期')"
                      :disabled="disabled"
                      valueFormat="YYYY-MM-DD HH:mm:ss"
                      v-model="model.beginTime"
                      style="width: 100%"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="1" style="text-align: center"
                  ><span>~</span></a-col
                >
                <a-col :span="10">
                  <a-form-model-item prop="endTime">
                    <a-date-picker
                      :show-time="{ defaultValue: moment('23:59:59', 'HH:mm:ss') }"
                      :placeholder="$t('请选择结束日期')"
                      :disabled="disabled"
                      valueFormat="YYYY-MM-DD HH:mm:ss"
                      v-model="model.endTime"
                      style="width: 100%"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="3">
                  <a-button type="primary" @click="setLongTime" :disabled="disabled">{{ $t('不限期') }}</a-button>
                </a-col>
              </a-row>
            </a-form-model-item>
          </a-col>
          <a-col :span="24" v-if="model.type && (model.type == 6 || model.type == 7)">
            <a-form-model-item :label="$t('c_有效日')" :labelCol="labelCol" :wrapperCol="wrapperCol1" required>
              <a-checkbox-group v-model="model.weeks" style="margin-top: 6px; margin-left: 5px">
                <a-checkbox style="margin-left: 8px" :value="item.key" :disabled="disabled" v-for="item in weeks" :key="item.key">{{
                  item.name
                }}</a-checkbox>
              </a-checkbox-group>
            </a-form-model-item>
          </a-col>
          <a-col v-if="model.type && model.type != 4" :span="24">
            <a-form-model-item :label="$t('发放条件')" :labelCol="labelCol" :wrapperCol="wrapperCol1">
              <div>
                <a-row v-for="(cond, ind) in allCond" :key="ind">
                  <a-col span="6" style="text-align: right"> {{ $t(cond.columnName) }}： </a-col>
                  <a-col span="16" v-if="cond.type == 3">
                    <a-select
                      v-model="model[cond.columnId]"
                      mode="multiple"
                      :placeholder="$t('请选择会员')"
                      :disabled="disabled"
                    >
                      <a-select-option
                        v-for="(item, index) in dictOptions[cond.datas]"
                        :key="index"
                        :value="item[cond.value]"
                        >{{ item[cond.text] }}</a-select-option
                      >
                    </a-select>
                  </a-col>
                  <a-col span="6" v-if="cond.type == 4">
                    <a-select v-model="model[cond.columnId + 'Query']" :disabled="disabled">
                      <a-select-option v-for="(item, index) in conds" :key="index" :value="item.value">{{
                        item.title
                      }}</a-select-option>
                    </a-select>
                  </a-col>
                  <a-col span="10" v-if="cond.type == 4">
                    <a-input v-model="model[cond.columnId]" :disabled="disabled" oninput="value=value.replace(/\D/g,'');" />
                  </a-col>
                  <a-col span="18" v-if="cond.type == 6">
                    <a-date-picker
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD 00:00:00"
                      v-model="model[cond.columnId + 'Begin']"
                      :placeholder="$t('请选择开始日期')"
                      :disabled="disabled"
                    ></a-date-picker
                    > ~
                    <a-date-picker
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD 23:59:59"
                      v-model="model[cond.columnId + 'End']"
                      :placeholder="$t('请选择结束日期')"
                      :disabled="disabled"
                    ></a-date-picker>
                  </a-col>
                </a-row>
              </div>
            </a-form-model-item>
          </a-col>
          <a-col :span="24" v-if="model.type && model.type == 3">
            <a-form-model-item :label="$t('领取时间')" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="getTimeType">
              <a-radio-group v-model="model.getTimeType" :disabled="disabled">
                <a-radio value="0">{{ $t('生日当天') }}</a-radio>
                <a-radio value="1">{{ $t('生日当月') }}</a-radio>
                <a-radio value="2">{{ $t('指定天数') }}</a-radio>
              </a-radio-group>
              <i18n path="collect-time" tag="div" v-if="model.getTimeType && model.getTimeType == 2">
                <a-input-number place="before" :min="0" v-model="model.getTimeBefore" />
                <a-input-number place="after" :min="0" v-model="model.getTimeAfter" />
              </i18n>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item required :label="$t('优惠券')" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-table
                :columns="columns"
                :dataSource="dataSource"
                ref="table"
                size="middle"
                bordered
                rowKey="id"
                :pagination="false"
                :loading="false"
                class="j-table-force-nowrap"
              >
                <template slot="couponName" slot-scope="text, record">
                  <a-select
                    showSearch
                    :placeholder="$t('请选择')"
                    style="width: 200px"
                    :pagination="false"
                    v-model="record.goodsId"
                    @search="handleSearch"
                    @change="handleChange"
                    :disabled="disabled"
                  >
                    <a-select-option v-for="d in couponList" :key="d.id">{{ d.name }}</a-select-option>
                  </a-select>
                </template>
                <template slot="amount" slot-scope="text, record">
                  <a-input-number v-model="record.amount" />
                </template>
                <template slot="action" slot-scope="text, record">
                  <a-icon type="close" @click="deleteGoods(text, record)" />
                </template>
              </a-table>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item :label="$t('备注')" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-textarea v-model="model.comment" :row="2" :disabled="disabled"></a-textarea>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
import Vue from 'vue'
import moment from 'moment'
import { getAction, httpAction } from '@/api/manage'
import { initDictOptions } from '@/components/dict/JDictSelectUtil'
let _self
export default {
  name: 'CouponActivityModal',
  components: {},
  data() {
    return {
      moment,
      width: 700,
      title: '',
      visible: false,
      confirmLoading: false,
      model: {
        type: '',
        getTimeType: '0',
        getTimeBefore: 0,
        getTimeAfter: 0,
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 17 },
      },
      wrapperCol1: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
      disabled: false,
      list: [],
      dataSource: [],
      columns0: [
        {
          title: this.$t('优惠券名称'),
          align: 'center',
          dataIndex: 'goodsId',
          scopedSlots: { customRender: 'couponName' },
        },
        {
          title: this.$t('数量'),
          align: 'center',
          dataIndex: 'amount',
          scopedSlots: { customRender: 'amount' },
        },
        {
          title: '+',
          dataIndex: 'action',
          align: 'center',
          width: 30,
          customHeaderCell: function (column) {
            return {
              style: {
                textAlign: 'center',
                color: '#1890ff',
                fontSize: '25px',
                lineHeight: '25px',
                fontWeight: 'bold',
                cursor: 'pointer',
              },
              on: {
                click: () => {
                  _self.addGoods()
                },
              },
            }
          },
          customCell: function (column) {
            return {
              style: {
                textAlign: 'center',
                color: '#1890ff',
                fontSize: '16px',
                height: '32px',
                lineHeight: '32px',
                fontWeight: 'bold',
                cursor: 'pointer',
              },
            }
          },
          scopedSlots: { customRender: 'action' },
        },
      ],
      columns1: [
        {
          title: this.$t('优惠券名称'),
          align: 'center',
          dataIndex: 'goodsId_dictText',
        },
        {
          title: this.$t('数量'),
          align: 'center',
          dataIndex: 'amount',
        },
      ],
      columns: [],
      couponList: [],
      rules: {
        type: [{ required: true, message: this.$t('请选择发放类型') }],
        beginTime: [{ required: true, message: this.$t('请选择开始日期') }],
        endTime: [{ required: true, message: this.$t('请选择结束日期') }],
      },
      dictOptions: {
        members: [],
      },
      conds: [
        { value: '>', title: this.$t('大于') },
        { value: '>=', title: this.$t('大于等于') },
        { value: '<', title: this.$t('小于') },
        { value: '<=', title: this.$t('小于等于') },
        { value: '=', title: this.$t('等于') },
      ],
      allCond: [],
      weeks: [
        { key: '1', name: this.$t('周一') },
        { key: '2', name: this.$t('周二') },
        { key: '3', name: this.$t('周三') },
        { key: '4', name: this.$t('周四') },
        { key: '5', name: this.$t('周五') },
        { key: '6', name: this.$t('周六') },
        { key: '7', name: this.$t('周日') },
      ],
      weekList: [],
    }
  },
  created() {
    _self = this
    let dictCode = 'bis_member_rule,name,id'
    getAction(`/sys/dict/getDictItems/${dictCode}`, {}).then((res) => {
      if (res.success) {
        this.$set(this.dictOptions, 'members', res.result)
      }
    })
    getAction('/query/bisQuery/getByTitle', { title: 'couponSet' }).then((res) => {
      if (res.success) {
        this.allCond = res.result.records[0].bisQueryItemList
        this.allCond.forEach((ac) => {
          if (ac.isHidden == 0) {
            if (ac.columnId == 'memberTypes') {
              ac.datas = 'members'
              ac.value = 'value'
              ac.text = 'text'
            }
          }
        })
      }
    })
  },
  methods: {
    setLongTime() {
      this.$set(this.model, 'beginTime', moment().format('YYYY-MM-DD 00:00:00'))
      this.$set(this.model, 'endTime', moment('2099-12-31 23:59:59').format('YYYY-MM-DD 23:59:59'))
      this.$refs.dataForm.validateField('beginTime')
      this.$refs.dataForm.validateField('endTime')
    },
    add() {
      this.visible = true
      this.model = {
        type: '',
        state: '1',
        beginTime: '',
        endTime: '',
        coinQuery: '>',
        lotteryQuery: '>',
        integralQuery: '>',
        growthQuery: '>',
        storedValueNumQuery: '>',
        getTimeType: '0',
        getTimeBefore: 0,
        getTimeAfter: 0,
        weeks: ['1', '2', '3', '4', '5', '6', '7'],
      }
      this.edit(this.model)
    },
    edit(record, state) {
      this.visible = true
      this.disabled = state
      this.$nextTick(() => {
        this.$refs.dataForm.clearValidate()
      })
      if (state) {
        this.columns = this.columns1
      } else {
        this.columns = this.columns0
      }
      this.model = Object.assign({}, record)
      this.dataSource = []
      initDictOptions('bis_coupon_set.type').then((res) => {
        if (res.success) {
          this.list = res.result
        }
      })
      if (this.model.id) {
        this.model.type = JSON.stringify(this.model.type)
        this.model.state = JSON.stringify(this.model.state)
        this.model.getTimeType = JSON.stringify(this.model.getTimeType)
        getAction('/coupon/bisCouponSetWeek/list', { couponSetId: this.model.id }).then((res) => {
          if (res.success) {
            this.weekList = res.result.records
            let arr = res.result.records.map((r) => {
              return '' + r.week
            })
            this.$set(this.model, 'weeks', arr)
          }
        })
        getAction('/coupon/bisCouponSet/queryBisCouponSetDetailByMainId', { id: this.model.id }).then((res) => {
          if (res.success) {
            this.dataSource = res.result.records
          }
        })
        getAction('/coupon/bisCouponSet/queryBisCouponSetQueryItemByMainId', { id: this.model.id }).then((res) => {
          if (res.success) {
            let getItems = res.result,
              query = {}
            getItems.forEach((vq) => {
              let obj1 = this.allCond.filter((sc) => {
                return vq.queryItemId == sc.id
              })[0]
              obj1.queryResultId = vq.id
              if (obj1.type == 1 || obj1.type == 1) {
                query[obj1.columnId] = vq.firstValue
              }
              if (obj1.type == 3) {
                query[obj1.columnId] = []
                vq.checkList.forEach((cs) => {
                  query[obj1.columnId].push(cs.checkId)
                })
              }
              if (obj1.type == 4 || obj1.type == 5) {
                query[obj1.columnId + 'Query'] = vq.firstValue
                query[obj1.columnId] = vq.secondValue
              }
              if (obj1.type == 6 || obj1.type == 7) {
                query[obj1.columnId + 'Begin'] = vq.firstValue
                query[obj1.columnId + 'End'] = vq.secondValue
              }
              if (obj1.type == 8) {
                query[obj1.columnId + 'Query'] = vq.firstValue
                let arr = vq.thirdValue.split(',')
                query[obj1.columnId + '1'] = arr[0]
                query[obj1.columnId + '2'] = arr[1]
                query[obj1.columnId + '3'] = arr[2]
              }
            })
            this.model = Object.assign({}, this.model, query)
          }
        })
      }
      this.getCoupon()
    },
    addGoods() {
      let obj = {
        goodsId: '',
        amount: '',
      }
      this.dataSource.push(obj)
    },
    deleteGoods(text, record) {
      this.dataSource.forEach((item) => {
        if (item.goodsId == record.goodsId) {
          let index = this.dataSource.indexOf(item)
          this.dataSource.splice(index, 1)
        }
      })
    },
    handleSearch(e) {
      this.getCoupon(e)
    },
    handleChange(item) {},
    getCoupon(info) {
      let query = {
        goodsInfo: info,
        form: 9,
        state: 'Y',
        pageNo: 1,
        pageSize: 999,
        tenantId: Vue.ls.get('TENANT_ID')?Vue.ls.get('TENANT_ID'):0
      }
      getAction('/goods/bisGoodsInfor/list', query).then((res) => {
        if (res.success) {
          this.couponList = res.result.records
        }
      })
    },
    handleOk() {
      let that = this
      that.$refs.dataForm.validate((valid) => {
        if (valid) {
          let querydata = Object.assign({}, that.model)
          if (that.model.state == '') {
            that.$message.warning(that.$t('请选择活动状态'))
            return
          }
          if (moment(that.model.beginTime) >= moment(that.model.endTime)) {
            that.$message.warning(that.$t('结束日期应晚于开始日期'))
            return
          }
          if (that.model.weeks.length == 0) {
            that.$message.warning(that.$t('至少选择一个有效日'))
            return
          }
          let arr = that.model.weeks.map((w) => {
            let dtl = {
              week: w,
            }
            let obj = that.weekList.find((wl) => {
              return wl.week == w
            })
            if (obj) {
              dtl = Object.assign({}, dtl, obj)
            }
            return dtl
          })
          querydata.weekList = arr
          let i = 0
          if (that.dataSource.length == 0) {
            that.$message.warning(that.$t('请添加优惠券活动'))
            return
          } else {
            that.dataSource.forEach((col) => {
              if (col.goodsId == '') {
                that.$message.warning(that.$t('请选择优惠券'))
                return
              } else {
                if (col.amount == '') {
                  that.$message.warning(that.$t('请输入数量'))
                  return
                } else {
                  i++
                }
              }
            })
          }
          let getItems = []
          for (var key in that.model) {
            let x = that.allCond.findIndex((si) => {
              return si.columnId == key || si.columnId + 'Begin' == key
            })
            if (that.model[key] != '' && x > -1) {
              let dtl = that.allCond[x],
                obj = {}
              obj.queryItemId = dtl.id
              if (dtl.queryResultId) {
                obj.id = dtl.queryResultId
              }
              if (dtl.type == 1 || dtl.type == 2) {
                obj.firstValue = that.model[key]
              }
              if (dtl.type == 3) {
                obj.checkList = []
                that.model[key].forEach((qd) => {
                  obj.checkList.push({
                    checkId: qd,
                  })
                })
              }
              if (dtl.type == 4 || dtl.type == 5) {
                obj.firstValue = that.model[key + 'Query']
                obj.secondValue = that.model[key]
              }
              if (dtl.type == 6 || dtl.type == 7) {
                obj.firstValue = that.model[key]
                obj.secondValue = that.model[key.slice(0, key.length - 5) + 'End']
              }
              if (dtl.type == 8) {
                obj.firstValue = that.model[key + 'Query']
                obj.secondValue = that.model[key]
                if (that.model[key + '1'] == undefined || that.model[key + '1'] == null) {
                  that.model[key + '1'] = ''
                }
                if (that.model[key + '2'] == undefined || that.model[key + '2'] == null) {
                  that.model[key + '2'] = ''
                }
                if (that.model[key + '3'] == undefined || that.model[key + '3'] == null) {
                  that.model[key + '3'] = ''
                }
                obj.thirdValue = that.model[key + '1'] + ',' + that.model[key + '2'] + ',' + that.model[key + '3']
              }
              getItems.push(obj)
            }
          }
          if (getItems.length > 0) {
            querydata.bisCouponSetQueryItemList = getItems
          }
          if (i == that.dataSource.length) {
            querydata.bisCouponSetDetailList = that.dataSource
            let method = ''
            let url = ''
            if (that.model.id) {
              url = '/coupon/bisCouponSet/edit'
              method = 'put'
            } else {
              url = '/coupon/bisCouponSet/add'
              method = 'post'
            }
            that.confirmLoading = true
            httpAction(url, querydata, method)
              .then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.close()
                  that.$emit('ok')
                } else {
                  that.$message.warning(res.message)
                }
              })
              .finally(() => {
                that.confirmLoading = false
              })
          }
        }
      })
    },
    handleCancel() {
      this.close()
    },
    close() {
      this.visible = false
    },
  },
}
</script>
<style scoped>
.cus0-form .ant-form-item {
  margin-bottom: 16px;
}
</style>